
package com.carsite.webapp.action;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.carsite.Constants;
import com.carsite.model.ModuleMenu;
import com.carsite.model.QueryMap;
import com.carsite.model.Role;
import com.carsite.model.User;
import com.carsite.service.ModuleMenuManager;
import com.carsite.service.RoleManager;
import com.carsite.webapp.form.RoleForm;



/**
 * Action class to handle CRUD on a Role object
 *
 * @struts.action name="roleForm" path="/roles" scope="request"
 *  validate="false" parameter="method" input="mainMenu"
 * @struts.action name="roleForm" path="/editRole" scope="request"
 *  validate="false" parameter="method" input="list"
 * @struts.action name="roleForm" path="/saveRole" scope="request"
 *  validate="true" parameter="method" input="edit"
 * @struts.action-set-property property="cancellable" value="true"
 * @struts.action-forward name="edit" path="/WEB-INF/pages/roleForm.jsp"
 * @struts.action-forward name="list" path="/WEB-INF/pages/roleList.jsp"
 * @struts.action-forward name="rolePrivilege" path="/WEB-INF/pages/rolePrivilege.jsp"
 * @struts.action-forward name="search" path="/roles.html" redirect="true"
 * @struts.action-forward name="noRight" path="/front/front_noLogin.jsp"
 */
public final class RoleAction extends BaseAction {
    public ActionForward cancel(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        return mapping.findForward("search");
    }

    public ActionForward delete(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'delete' method");
        }
        if(!this.check(request)){
        	return mapping.findForward("noRight");
        }
        ActionMessages messages = new ActionMessages();
        RoleForm roleForm = (RoleForm) form;

        // Exceptions are caught by ActionExceptionHandler
        RoleManager mgr = (RoleManager) getBean("roleManager");
        //
        mgr.removeRole(new Long(Long.parseLong(roleForm.getId())));

        messages.add(ActionMessages.GLOBAL_MESSAGE,
                     new ActionMessage("role.deleted"));

        // save messages in session, so they'll survive the redirect
        saveMessages(request.getSession(), messages);

        return mapping.findForward("search");
    }

    public ActionForward edit(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'edit' method");
        }
        
        if(!this.check(request)){
        	return mapping.findForward("noRight");
        }
        RoleForm roleForm = (RoleForm) form;

        // if an id is passed in, look up the user - otherwise
        // don't do anything - user is doing an add
        if (roleForm.getId() != null) {
            RoleManager mgr = (RoleManager) getBean("roleManager");
            Role role = mgr.getRole(new Long(Long.parseLong(roleForm.getId())));
            roleForm = (RoleForm) convert(role);
            
            updateFormBean(mapping, request, roleForm);
        }
    
      // request.setAttribute(Constants.ROLE_LIST,roleList);
        return mapping.findForward("edit");
        
        /**
            if (log.isDebugEnabled()) {
            log.debug("Entering 'edit' method");
        }

        RoleForm roleForm = (RoleForm) form;

        // if an id is passed in, look up the user - otherwise
        // don't do anything - user is doing an add
        if (roleForm.getId() != null) {
            RoleManager mgr = (RoleManager) getBean("roleManager");
            Role role = mgr.getRole(roleForm.getId());
            roleForm = (RoleForm) convert(role);
            updateFormBean(mapping, request, roleForm);
        }

        return mapping.findForward("edit"); 
         */
    }

    public ActionForward save(ActionMapping mapping, ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'save' method");
        }
        if(!this.check(request)){
        	return mapping.findForward("noRight");
        }
        // Extract attributes and parameters we will need
        ActionMessages messages = new ActionMessages();
        RoleForm roleForm = (RoleForm) form;
        boolean isNew = ("".equals(roleForm.getId()) || roleForm.getId() == null);

        RoleManager mgr = (RoleManager) getBean("roleManager");
        Role role = (Role) convert(roleForm);
        
        String levels=new String("");
		String[] roleLevels=request.getParameterValues("roleLevels" );
		for (int i = 0; roleLevels != null &&  i < roleLevels.length; i++) {
			if (i!=roleLevels.length-1){
				levels =levels+ roleLevels[i]+",";
			}else
			{
				levels =levels+ roleLevels[i];
			}
            
        }
		role.setLevels( levels);
        
        mgr.saveRole(role);
        roleForm = (RoleForm) convert(role);
     
        // add success messages
        if (isNew) {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("role.added"));

            // save messages in session to survive a redirect
            saveMessages(request.getSession(), messages);

            return mapping.findForward("search");
        } else {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("role.updated"));
            saveMessages(request, messages);
            ///////////
            updateFormBean(mapping, request, roleForm);
            
            return mapping.findForward("edit");
        }
        
       /**
        if (log.isDebugEnabled()) {
            log.debug("Entering 'save' method");
        }

        // Extract attributes and parameters we will need
        ActionMessages messages = new ActionMessages();
        RoleForm roleForm = (RoleForm) form;
        boolean isNew = ("".equals(roleForm.getId()) || roleForm.getId() == null);

        RoleManager mgr = (RoleManager) getBean("roleManager");
        Role role = (Role) convert(roleForm);
        mgr.saveRole(role);

        // add success messages
        if (isNew) {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("role.added"));

            // save messages in session to survive a redirect
            saveMessages(request.getSession(), messages);

            return mapping.findForward("search");
        } else {
            messages.add(ActionMessages.GLOBAL_MESSAGE,
                         new ActionMessage("role.updated"));
            saveMessages(request, messages);

            return mapping.findForward("edit");
        }*/
    }

    public ActionForward search(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'search' method");
        }
        if(!this.check(request)){
        	return mapping.findForward("noRight");
        }
        RoleForm roleForm = (RoleForm) form;
        Role role = (Role) convert(roleForm);

        RoleManager mgr = (RoleManager) getBean("roleManager");
        request.setAttribute(Constants.ROLE_LIST, mgr.getRoles(role));
       
        return mapping.findForward("list");
    }
    public ActionForward unspecified(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response)
            throws Exception {
        return search(mapping, form, request, response);
    }

    
    //query roles by some query conditions
    
    public ActionForward queryRoles(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
		throws Exception {
			if (log.isDebugEnabled()) {
				log.debug("Entering 'queryRoles()' method");
		}
			if(!this.check(request)){
	        	return mapping.findForward("noRight");
	        }
		RoleForm roleForm = (RoleForm) form;
		Role role = (Role) convert(roleForm);
        
		RoleManager roleMgr = (RoleManager) getBean("roleManager");
		
		//取得查询条件，返回结果
		QueryMap queryMap = new QueryMap();
		//实现模糊查找
		queryMap.addCondition("name","like",roleForm.getName());          //角色代码
		queryMap.addCondition("cnName","like",roleForm.getCnName());            //角色名称

		//保存搜索字在输入框里头
		updateFormBean(mapping, request, roleForm);
		  
		request.setAttribute(Constants.ROLE_LIST, roleMgr.getRoleByConditions(queryMap));
		
        return mapping.findForward("list");
 	}    

   
    public ActionForward rolePrivilege(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
	throws Exception {
		if (log.isDebugEnabled()) {
		   log.debug("Entering 'rolePrivilege' method");
		}
		if(!this.check(request)){
        	return mapping.findForward("noRight");
        }
		RoleForm roleForm = (RoleForm) form;
		
		// if an id is passed in, look up the user - otherwise
		// don't do anything - user is doing an add
		if (roleForm.getId() != null) {
			RoleManager mgr = (RoleManager) getBean("roleManager");
			Role role = mgr.getRole(new Long(roleForm.getId()));
			roleForm = (RoleForm) convert(role);
			updateFormBean(mapping, request, roleForm);
			
			ModuleMenuManager menuMgr = (ModuleMenuManager) getBean("moduleMenuManager");
			List menuList = menuMgr.getModules();
			
			
			Map  selectedMenuMap = new HashMap();
			
			Iterator it = role.getPrivileges().iterator();
			while(it.hasNext()){
				ModuleMenu menu = (ModuleMenu)it.next();
			     selectedMenuMap.put(menu.getMenuId(),menu);
			}
			
			request.setAttribute(Constants.MODULEMENU_LIST, menuList);
			request.setAttribute("selectedMemuMap",selectedMenuMap);
		}
	
		return mapping.findForward("rolePrivilege");
	}
    
    public ActionForward rolePrivilegeSave(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
	throws Exception {
		if (log.isDebugEnabled()) {
		   log.debug("Entering 'rolePrivilegeSave' method");
		}
		if(!this.check(request)){
        	return mapping.findForward("noRight");
        }
		RoleForm roleForm = (RoleForm) form;
		
		// if an id is passed in, look up the user - otherwise
		// don't do anything - user is doing an add
		if (roleForm.getId() != null) {
			RoleManager mgr = (RoleManager) getBean("roleManager");
			
			Role role = mgr.getRole(new Long(roleForm.getId()));
			

			role.getPrivileges().clear();
			ModuleMenuManager menuMgr = (ModuleMenuManager) getBean("moduleMenuManager");
			ModuleMenu menu = null;
	       if(roleForm.getIds()!=null){
	            for(int i = 0 ; i< roleForm.getIds().length;i++){
	            	String menuStr = roleForm.getIds()[i];
	            	String[] menuArray = menuStr.split("-");
	            	menu = menuMgr.getModuleMenu(menuArray[1]);
	            	role.addPrivilege(menu);
	        	 }
	          
	        }
			
	        mgr.saveRole(role);
			
		}
		
		 return rolePrivilege(mapping, form, request, response);
		
	}
    public boolean check(HttpServletRequest request){
		 HttpSession session=request.getSession();
		 if(session==null){
			 return false;
		 }else{
			 User currentUser=(User)session.getAttribute("currentUser");
			 if(currentUser==null){
				 return false;
			 }else{
				 Set roles=currentUser.getRoles();
				 Iterator rolesIt=(Iterator)roles.iterator();
				 while(rolesIt.hasNext()){
					 Role role=(Role)rolesIt.next();
					 System.out.println(role.getName());
					 if(role.getName().equals("admin")){
						 return true;
					 }
				 }
				 return false;
			 }
		 }
		
	 }
    
    
    
}
